import { PlusIcon, Settings2Icon, TrashIcon, CheckIcon } from 'lucide-react'
import { memo, useCallback, useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Input } from '@/components/ui/input'
import { ScrollArea } from '@/components/ui/scroll-area'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import type { LiveStreamConfig, LiveStreamConfigPreset } from '@/hooks/useAIChat'
import { useAIChatStore } from '@/hooks/useAIChat'
import { useToast } from '@/hooks/useToast'
import { cn } from '@/lib/utils'

const emptyConfig: LiveStreamConfig = {
  positivePrompt: '',
  negativePrompt: '',
  role: '',
  productParams: '',
}

export const LiveStreamConfigDialog = memo(() => {
  const {
    liveStreamConfigs,
    activeLiveStreamConfigId,
    addLiveStreamConfig,
    updateLiveStreamConfig,
    deleteLiveStreamConfig,
    setActiveLiveStreamConfig,
  } = useAIChatStore()
  const { toast } = useToast()

  const [open, setOpen] = useState(false)
  const [selectedId, setSelectedId] = useState<string | null>(null)
  const [editingName, setEditingName] = useState('')
  const [editingConfig, setEditingConfig] = useState<LiveStreamConfig>(emptyConfig)
  const [isNew, setIsNew] = useState(false)
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
  const [deleteId, setDeleteId] = useState<string | null>(null)

  // 初始化选中项
  useEffect(() => {
    if (open) {
      if (activeLiveStreamConfigId && liveStreamConfigs.some((c: LiveStreamConfigPreset) => c.id === activeLiveStreamConfigId)) {
        setSelectedId(activeLiveStreamConfigId)
        const preset = liveStreamConfigs.find((c: LiveStreamConfigPreset) => c.id === activeLiveStreamConfigId)
        if (preset) {
          setEditingName(preset.name)
          setEditingConfig(preset.config)
          setIsNew(false)
        }
      } else if (liveStreamConfigs.length > 0) {
        setSelectedId(liveStreamConfigs[0].id)
        setEditingName(liveStreamConfigs[0].name)
        setEditingConfig(liveStreamConfigs[0].config)
        setIsNew(false)
      }
    }
  }, [open, activeLiveStreamConfigId, liveStreamConfigs])

  const handleSelectConfig = useCallback((preset: LiveStreamConfigPreset) => {
    setSelectedId(preset.id)
    setEditingName(preset.name)
    setEditingConfig(preset.config)
    setIsNew(false)
  }, [])

  const handleNewConfig = useCallback(() => {
    setSelectedId(null)
    setEditingName('')
    setEditingConfig(emptyConfig)
    setIsNew(true)
  }, [])

  const handleSave = useCallback(() => {
    if (!editingName.trim()) {
      toast.error('请输入配置名称')
      return
    }

    if (!editingConfig.role.trim()) {
      toast.error('请输入角色设定')
      return
    }

    if (!editingConfig.positivePrompt.trim()) {
      toast.error('请输入正向提示词')
      return
    }

    if (!editingConfig.negativePrompt.trim()) {
      toast.error('请输入反向提示词')
      return
    }

    if (isNew) {
      addLiveStreamConfig({
        name: editingName,
        config: editingConfig,
      })
      toast.success('配置已添加')
      setIsNew(false)
    } else if (selectedId) {
      updateLiveStreamConfig(selectedId, {
        name: editingName,
        config: editingConfig,
      })
      toast.success('配置已更新')
    }
  }, [isNew, selectedId, editingName, editingConfig, addLiveStreamConfig, updateLiveStreamConfig, toast])

  const handleDelete = useCallback((id: string) => {
    setDeleteId(id)
    setDeleteDialogOpen(true)
  }, [])

  const confirmDelete = useCallback(() => {
    if (deleteId) {
      deleteLiveStreamConfig(deleteId)
      toast.success('配置已删除')
      if (selectedId === deleteId) {
        setSelectedId(null)
        setEditingName('')
        setEditingConfig(emptyConfig)
        setIsNew(false)
      }
    }
    setDeleteDialogOpen(false)
    setDeleteId(null)
  }, [deleteId, selectedId, deleteLiveStreamConfig, toast])

  const handleFieldChange = useCallback(
    (field: keyof LiveStreamConfig, value: string) => {
      setEditingConfig(prev => ({
        ...prev,
        [field]: value,
      }))
    },
    [],
  )

  const handleActivate = useCallback((id: string) => {
    setActiveLiveStreamConfig(id)
    toast.success('已切换配置')
  }, [setActiveLiveStreamConfig, toast])

  return (
    <>
      <Dialog open={open} onOpenChange={setOpen}>
        <DialogTrigger asChild>
          <Button variant="outline" size="sm">
            <Settings2Icon className="mr-2 h-4 w-4" />
            直播配置
          </Button>
        </DialogTrigger>
        <DialogContent className="sm:max-w-[900px] max-h-[90vh] p-0">
          <DialogHeader className="px-6 pt-6 pb-4">
            <DialogTitle>直播场景配置</DialogTitle>
            <DialogDescription>
              管理不同直播场景的配置，可以快速切换不同类型的直播
            </DialogDescription>
          </DialogHeader>

          <div className="flex h-[600px]">
            {/* 左侧配置列表 */}
            <div className="w-64 border-r flex flex-col">
              <div className="p-4 border-b">
                <Button
                  onClick={handleNewConfig}
                  className="w-full"
                  size="sm"
                  variant="outline"
                >
                  <PlusIcon className="mr-2 h-4 w-4" />
                  新增配置
                </Button>
              </div>
              <ScrollArea className="flex-1">
                <div className="p-2 space-y-1">
                  {liveStreamConfigs.map((preset: LiveStreamConfigPreset) => (
                    <div
                      key={preset.id}
                      className={cn(
                        'group flex items-center justify-between p-3 rounded-lg cursor-pointer hover:bg-accent transition-colors',
                        selectedId === preset.id && 'bg-accent',
                      )}
                      onClick={() => handleSelectConfig(preset)}
                    >
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-2">
                          <span className="font-medium truncate">{preset.name}</span>
                          {activeLiveStreamConfigId === preset.id && (
                            <CheckIcon className="h-4 w-4 text-green-600 flex-shrink-0" />
                          )}
                        </div>
                      </div>
                      <Button
                        variant="ghost"
                        size="icon"
                        className="h-8 w-8 opacity-0 group-hover:opacity-100 transition-opacity"
                        onClick={e => {
                          e.stopPropagation()
                          handleDelete(preset.id)
                        }}
                      >
                        <TrashIcon className="h-4 w-4 text-destructive" />
                      </Button>
                    </div>
                  ))}
                  {liveStreamConfigs.length === 0 && (
                    <div className="text-center text-muted-foreground text-sm py-8">
                      暂无配置，点击上方按钮新增
                    </div>
                  )}
                </div>
              </ScrollArea>
            </div>

            {/* 右侧配置表单 */}
            <div className="flex-1 flex flex-col">
              {(selectedId || isNew) ? (
                <ScrollArea className="flex-1 px-6 py-4">
                  <div className="space-y-6">
                    <div className="space-y-2">
                      <Label htmlFor="name">配置名称 *</Label>
                      <Input
                        id="name"
                        value={editingName}
                        onChange={e => setEditingName(e.target.value)}
                        placeholder="例如：美妆直播、数码产品直播"
                        className="w-full"
                      />
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="role">
                        角色设定 <span className="text-destructive">*</span>
                      </Label>
                      <Input
                        id="role"
                        value={editingConfig.role}
                        onChange={e => handleFieldChange('role', e.target.value)}
                        placeholder="例如：专业的美妆主播、热情的数码产品推荐师"
                        required
                      />
                      <p className="text-xs text-muted-foreground">
                        定义 AI 助手的角色身份
                      </p>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="productParams">产品参数</Label>
                      <Textarea
                        id="productParams"
                        value={editingConfig.productParams}
                        onChange={e => handleFieldChange('productParams', e.target.value)}
                        placeholder="例如：产品名称、规格、价格、特点等关键信息"
                        className="min-h-[80px] max-h-[300px] resize-y"
                      />
                      <p className="text-xs text-muted-foreground">
                        可拖动右下角调整高度
                      </p>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="positivePrompt">
                        正向提示词 <span className="text-destructive">*</span>
                      </Label>
                      <Textarea
                        id="positivePrompt"
                        value={editingConfig.positivePrompt}
                        onChange={e => handleFieldChange('positivePrompt', e.target.value)}
                        placeholder="例如：回复要热情、亲切、专业，突出产品优势"
                        className="min-h-[80px] max-h-[300px] resize-y"
                        required
                      />
                      <p className="text-xs text-muted-foreground">
                        可拖动右下角调整高度
                      </p>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="negativePrompt">
                        反向提示词 <span className="text-destructive">*</span>
                      </Label>
                      <Textarea
                        id="negativePrompt"
                        value={editingConfig.negativePrompt}
                        onChange={e => handleFieldChange('negativePrompt', e.target.value)}
                        placeholder="例如：不要使用过于正式的语言，不要做过度承诺"
                        className="min-h-[80px] max-h-[300px] resize-y"
                        required
                      />
                      <p className="text-xs text-muted-foreground">
                        可拖动右下角调整高度
                      </p>
                    </div>
                  </div>
                </ScrollArea>
              ) : (
                <div className="flex-1 flex items-center justify-center text-muted-foreground">
                  <div className="text-center">
                    <Settings2Icon className="h-12 w-12 mx-auto mb-4 opacity-50" />
                    <p>请选择或新增配置</p>
                  </div>
                </div>
              )}

              {/* 底部操作按钮 */}
              {(selectedId || isNew) && (
                <div className="border-t px-6 py-4 flex gap-2 justify-end">
                  {!isNew && selectedId && activeLiveStreamConfigId !== selectedId && (
                    <Button
                      variant="outline"
                      onClick={() => handleActivate(selectedId)}
                    >
                      设为当前配置
                    </Button>
                  )}
                  <Button onClick={handleSave}>
                    {isNew ? '添加配置' : '保存修改'}
                  </Button>
                </div>
              )}
            </div>
          </div>
        </DialogContent>
      </Dialog>

      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认删除</AlertDialogTitle>
            <AlertDialogDescription>
              确定要删除这个配置吗？此操作无法撤销。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={confirmDelete}>删除</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
})

LiveStreamConfigDialog.displayName = 'LiveStreamConfigDialog'

